import datetime
from datetime import datetime as dt

import requests
import tushare as ts


def get_day_type(query_date):
    url = 'http://tool.bitefu.net/jiari/?d=' + query_date
    # 上面的url接口  工作日对应结果为 0, 休息日对应结果为 1, 节假日对应的结果为 2；
    # url = 'http://www.easybots.cn/api/holiday.php?d=' + query_date  需要实名认证
    # 返回数据：正常工作日对应结果为 0, 法定节假日对应结果为 1, 节假日调休补班对应的结果为 2，休息日对应结果为 3
    # url = 'https://api.goseek.cn/Tools/holiday?date=' + query_date
    # 返回数据：正常工作日对应结果为 0, 法定节假日对应结果为 1, 节假日调休补班对应的结果为 2，休息日对应结果为 3
    # 20190528
    response = requests.get(url=url)
    content = response.text  # str 类型的
    # {"code":10000,"data":0}
    # print("content=" + content)
    return content


# 判断当天是否是交易日
def today_is_trade_day():
    query_date = datetime.datetime.strftime(datetime.datetime.today(), '%Y%m%d')
    print(datetime.datetime.today())
    day_type = get_day_type(query_date)
    if day_type.__eq__(0):
        return True
    else:
        return False


# 判断当前时间是否是交易时间
def is_trade_time():
    if not today_is_trade_day():
        return False

    # 当前时间
    n_time = datetime.datetime.now()

    # 范围时间
    d_time = datetime.datetime.strptime(str(datetime.datetime.now().date()) + '9:30', '%Y-%m-%d%H:%M')
    d_time1 = datetime.datetime.strptime(str(datetime.datetime.now().date()) + '11:30', '%Y-%m-%d%H:%M')
    d_time2 = datetime.datetime.strptime(str(datetime.datetime.now().date()) + '13:00', '%Y-%m-%d%H:%M')
    d_time3 = datetime.datetime.strptime(str(datetime.datetime.now().date()) + '15:00', '%Y-%m-%d%H:%M')

    # 判断当前时间是否在范围时间内
    if (d_time < n_time < d_time1) or (d_time2 < n_time < d_time3):
        return True
    return False


# 判断是否是当前周最后一个交易日
def is_last_trade_day(day):
    # today = time.strftime('%Y%m%d', time.strptime(day, "%Y-%m-%d %H:%M:%S"))
    today = parse_ymd(day).strftime('%Y%m%d')
    # print(today)
    tomorrow = (parse_ymd(day) + datetime.timedelta(days=1)).strftime('%Y%m%d')
    # print(tomorrow)
    if get_day_type(today) == '0' and (get_day_type(tomorrow) == '1' or get_day_type(tomorrow) == '2'):
        return True
    return False


def parse_ymd(s):
    strip = s[0:10]
    year_s, mon_s, day_s = strip.split('-')
    return dt(int(year_s), int(mon_s), int(day_s))


def test():
    alldays = ts.trade_cal()
    tradingdays = alldays[alldays['isOpen'] == 1]  # 开盘日
    today = datetime.datetime.today().strftime('%Y-%m-%d')
    if today in tradingdays['calendarDate'].values:
        print(1)
        tradingdays_list = tradingdays['calendarDate'].tolist()
        today_index = tradingdays_list.index(today)
        last_day = tradingdays_list[int(today_index) - 1]
    print(0)


if __name__ == '__main__':
    print(today_is_trade_day())
    print(is_trade_time())

    # weekday = parse_ymd("2021-07-16 07:30:02").weekday()
    # print(weekday)
    # test()
    # # result = is_last_trade_day("2021-07-16")
    # result = is_last_trade_day("2021-07-16 07:30:02")
    # print(result)
